//
//  NDLoginInfo.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/16.
//

import SwiftUI
import Combine

let loginKey = "isUserLoggedIn"
let tokenKey = "userToken"

class NDLoginInfo: ObservableObject {
    static let shared = NDLoginInfo()
    
    @Published var shouldPresentLogInView: Bool = false
    private var cancellables = Set<AnyCancellable>()
    
    var isLogined: Bool {
        if let _ = NDUserDefaults.shared.retrieveText(for: NDAccountIdentifierKey) {
            return true
        }
        return false
    }
    
    private init() {
        NotificationCenter.default.publisher(for: .logoutNotification, object: nil)
            .sink { [weak self] notification in
                guard let self = self else { return }
                self.logout()
            }
            .store(in: &cancellables)
        
        NotificationCenter.default.publisher(for: .loginInvalidNotification, object: nil)
            .sink { [weak self] notification in
                guard let self = self else { return }
                self.loginInvalid()
            }
            .store(in: &cancellables)
    }
    
    func loginInvalid() {
        // 清除所有登录信息
        NDUserDefaults.shared.removeEntry(for: NDAccountIdentifierKey)
        shouldPresentLogInView = true
        print("登录失效")
    }
    
    func logout() {
        NDUserDefaults.shared.removeEntry(for: NDAccountIdentifierKey)
        NDAppState.shared.rootView = .login
        print("用户已退出登录")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
